package com.le.medium.class3;

import org.junit.Test;

/**
 * 用zigzag的方式打印矩阵，比如如下的矩阵
 * 0  1  2  3
 * 4  5  6  7
 * 8  9 10 11
 * 打印顺序为：0 1 4 8 5 2 3 6 9 10 7 11
 */
public class Problem02_ZigZagPrintMatrix {

    public static void printMatrixZigZag(int[][] matrix) {
        int ar = 0;
        int ac = 0;
        int br = 0;
        int bc = 0;
        int row = matrix.length - 1;
        int col = matrix[0].length - 1;
        boolean flag = false;
        while (ar != row + 1) {
            // 打印对角线
            printEdge(matrix, ac, ar, bc, br, flag);
            // 书写位置不可颠倒,否则数组越界
            ar = ac == col ? ar + 1 : ar;
            ac = ac == col ? ac : ac + 1;
            bc = br == row ? bc + 1 : bc;
            br = br == row ? br : br + 1;
            flag = !flag;
        }
    }

    public static void printEdge(int[][] matrix, int ac, int ar, int bc, int br, boolean flag) {
        if (flag) {
            // 右上到左下打印
            while (ar != br + 1) {
                System.out.print(matrix[ar++][ac--] + "  ");
            }
        } else {
            // 坐下到右上打印
            while (br != ar - 1) {
                System.out.print(matrix[br--][bc++] + "  ");
            }
        }
    }

    @Test
    public void test() {
        int[][] matrix = {
                {0, 1, 2, 3},
                {4, 5, 6, 7},
                {8, 9, 10, 11}
        };
        printMatrixZigZag(matrix);
    }
}
